package com.ai.service.made.impl;

import com.ai.common.CommonResponse;
import com.ai.entity.made.RegionBase;
import com.ai.entity.made.page.RegionPage;
import com.ai.entity.security.SysPermission;
import com.ai.entity.security.SysRolePermissionRelation;
import com.ai.mapper.RegionBaseMapper;
import com.ai.model.vo.RegionBaseVo;
import com.ai.service.made.IRegionBaseService;
import com.ai.service.made.IRegionManageService;
import com.ai.service.security.ISysPermissionService;
import com.ai.service.security.ISysRolePermissionRelationService;
import com.ai.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiaok
 * @since 2023-07-24
 */
@Service
@Slf4j
public class RegionBaseServiceImpl extends ServiceImpl<RegionBaseMapper, RegionBase> implements IRegionBaseService {

    @Resource
    private ISysPermissionService iSysPermissionService;


    @Resource
    private ISysRolePermissionRelationService iSysRolePermissionRelationService;


    @Resource
    private IRegionManageService iRegionManageService;

    /**
     * 获取所有的区域基本信息
     * @return
     */
    @Override
    public CommonResponse getList() {
        List<RegionBase> list =
                list();
        return CommonResponse.ok(list);
    }

    /**
     * 删除区域信息
     * @return
     */
    @Override
    @Transactional
    public CommonResponse deleteRegion(String id) {

        RegionBase regionBase = this.getById(id);
        
        //先删除对应的权限表中的数据
        SysPermission sysPermission = iSysPermissionService.getPermissionByCode(regionBase.getRegionCode());
        /**
         * 如果当前区域被其他角色所绑定，则不允许删除
         */
        List<SysRolePermissionRelation> list = iSysRolePermissionRelationService.list(new QueryWrapper<SysRolePermissionRelation>().eq("permission_id", sysPermission.getId()));

        if (!Collections.isEmpty(list)){
            return CommonResponse.error("当前区域正在被使用，禁止删除");
        }
        //删除权限表中的数据
        iSysPermissionService.removeById(sysPermission);
        // : 2023-07-24 删除区域信息
        this.baseMapper.deleteById(id);
        //删除当前区域与摄像头之间的绑定关系
        iRegionManageService.removeRelationByRegionId(id);

        return CommonResponse.ok();
    }

    /**
     * 新增区域信息
     * 新增的同时，在权限表中也要新增
     * @param regionBaseVo
     * @return
     */
    @Override
    @Transactional
    public CommonResponse add(RegionBaseVo regionBaseVo) {

        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();

        //区域代码不能重复
        RegionBase db=getRegionBaseByCode(regionBaseVo.getRegionCode());
        if (db != null){
            return CommonResponse.error("当前区域代码已存在");
        }

        /**
         * 抽离出权限部分所需要的内容
         */
        SysPermission sysPermission = new SysPermission();
        sysPermission.setPermissionCode(regionBaseVo.getRegionCode());
        sysPermission.setPermissionName(regionBaseVo.getRegionName());
        sysPermission.setIsRegionManage("1");
        boolean save = iSysPermissionService.save(sysPermission);
        if (!save){
            log.info("===========================  区域信息提取至权限表失败  ===========================");
            return CommonResponse.error("保存失败，请重新尝试操作");
        }

        String userName = SecurityUtils.getLoginUserName();

        RegionBase regionBase = new RegionBase();
        regionBase.setRegionCode(regionBaseVo.getRegionCode());
        regionBase.setRegionName(regionBaseVo.getRegionName());
        regionBase.setPhone(regionBaseVo.getPhone());
        regionBase.setResponsibility(regionBaseVo.getResponsibility());
        regionBase.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        regionBase.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // : 2023-07-24 当前用户的登录信息

        regionBase.setCreateUser(userName);
        regionBase.setUpdateUser(userName);

        //保存区域信息
        int insert = this.baseMapper.insert(regionBase);
        if (insert != 1){
            log.info("===========================  区域信息保存失败  ===========================");
            return CommonResponse.error("保存失败，请重新尝试操作");
        }

        return CommonResponse.ok();
    }

    /**
     * 根据区域code查询该区域是否存在
     * @param regionCode
     * @return
     */
    @Override
    public RegionBase getRegionBaseByCode(String regionCode) {

        return this.getOne(new QueryWrapper<RegionBase>().eq("region_code", regionCode));

    }

    /**
     * 区域分页查询
     * @param pageParam
     * @return
     */
    @Override
    public IPage<RegionBase> getPage(RegionPage pageParam) {

        QueryWrapper<RegionBase> wrapper = pageParam.getQuery(new QueryWrapper<>());

        RegionPage page = this.page(pageParam, wrapper);

        return page;
    }

    /**
     * 通过id获取指定的区域信息
     * @param id
     * @return
     */
    @Override
    public CommonResponse getAppoint(String id) {
        RegionBase regionBase = getById(id);
        if ( regionBase != null ){
            return CommonResponse.ok(regionBase);
        }
        return CommonResponse.error("数据不存在");
    }

    /**
     * 更新区域信息
     * @param regionBase
     * @return
     */
    @Override
    @Transactional
    public CommonResponse updateRegion(RegionBase regionBase) {

        //首先获取DB中的该行数据
        RegionBase dbBase = this.getById(regionBase.getId());
        String oldRegionCode = dbBase.getRegionCode();

        //查询权限表中对应的数据
        SysPermission permission=  iSysPermissionService.getPermissionByCode(oldRegionCode);

        if (permission == null){
            log.info("===========================  区域对应的权限信息不存在  ===========================");
            return CommonResponse.error("修改失败");
        }

        //更新区域信息数据、权限数据
        boolean b = this.updateById(regionBase);
        if (!b){
            log.info("===========================  修改区域信息失败 ===========================");
            throw new RuntimeException("修改区域信息失败");
//            return CommonResponse.error("修改失败");
        }


        permission.setPermissionCode(regionBase.getRegionCode());
        permission.setPermissionName(regionBase.getRegionName());
        permission.setIsRegionManage("1");
        boolean b1 = iSysPermissionService.updateById(permission);
        if (!b1){
            log.info("===========================  修改权限信息失败 ===========================");
            throw new RuntimeException("修改权限信息失败");
//            return CommonResponse.error("修改失败");
        }

        return CommonResponse.ok("区域信息更新成功");
    }

    @Override
    public RegionBase getRegionByCameraId(Integer cameraId) {

        RegionBase regionBase =  this.baseMapper.getRegionByCameraId(cameraId);


        return regionBase;
    }
}
